package com.softserve.academy.food.services;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.softserve.academy.food.dao.HibernateUser;
import com.softserve.academy.food.entity.eUser;
import com.softserve.academy.food.model.mUserCredentials;
import com.softserve.academy.food.model.mUserInfo;
import com.softserve.academy.food.security.Coding;

@Service
public class userService implements iUserService
{
	@Autowired
	private HibernateUser daoUser;
	
	@Transactional
	public boolean checkUser( String login )
	{
		if ( login!=null )
		{ 
			ArrayList<eUser> list = (ArrayList<eUser>)  daoUser.ReadAll();
		
			for (eUser user : list)
			{
				if ( user.getLogin().equals(login) )
				{
					return true;
				}
			}
		} 
		return false;
	}
	
	@Transactional
	public void addUser(mUserCredentials user)
	{
		if (user!=null)
		{
			Coding code = new Coding();
			user.setPass( code.getHash(user.getPass()) );
			
			eUser newUser = new eUser( user );
			
			newUser = daoUser.Create( newUser );
		}
	}
	
	@Transactional
	public mUserInfo getUser(String login)
	{
		mUserInfo user = new mUserInfo( daoUser.getUser(login) );
		
		return user;
	}
	
	@Transactional
	public void updateUser( mUserInfo user )
	{
		if (user!=null)
		{
			eUser oldUser = daoUser.Read( user.getId() );
			
			oldUser.setFistname( user.getFistname() );
			oldUser.setPhone( user.getPhone() );
			oldUser.setLastname( user.getLastname() );
			oldUser.setMail( user.getMail() );

			daoUser.Update( oldUser );
		}
	}
	

}
